package com.chat.xx.server.impl;

import com.chat.xx.beam.common.Message;
import com.chat.xx.beam.common.PageBeam;
import com.chat.xx.beam.entity.ContentEntity;
import com.chat.xx.beam.vo.add.ContentAdd;
import com.chat.xx.beam.vo.query.ContentQuery;
import com.chat.xx.beam.websocketBackContent.WebsocketContent;
import com.chat.xx.config.webSocket.MyWebSocketHandler;
import com.chat.xx.mapper.ContentMapper;
import com.chat.xx.server.ContentServer;
import com.chat.xx.server.UserServer;
import com.chat.xx.utiles.SetMessage;
import com.chat.xx.utiles.Tool;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ContentServerImpl implements ContentServer {
    @Autowired
    private final ContentMapper contentMapper;
    private final UserServer userServer;
    public ContentServerImpl(ContentMapper contentMapper, UserServer userServer) {
        this.contentMapper = contentMapper;
        this.userServer = userServer;
    }
    @Override
    public Message<Boolean> add(ContentAdd content){
        ContentEntity contentEntity = new ContentEntity();
        BeanUtils.copyProperties(content,contentEntity);
        int sel = contentMapper.insertSelective(contentEntity);
        if(sel == 0){
            return SetMessage.set(201,"失败",false);
        }else {
            String name = userServer.getUserNameById(content.getU_id());
            WebsocketContent websocketContent = new WebsocketContent();
            BeanUtils.copyProperties(content,websocketContent);
            websocketContent.setU_name(name);
            MyWebSocketHandler.sendAllMessage(Tool.wbSendMsg("SEND_MSG",websocketContent));
            return SetMessage.set(200,"成功",true) ;
        }
    }
    @Override
    public Message<PageBeam<ContentQuery>> list(ContentQuery contentQuery){
        PageHelper.startPage(contentQuery.getPageNum(), contentQuery.getPageSize());
        List<ContentQuery> list = contentMapper.getList(contentQuery);

        if(list.isEmpty()){
            return SetMessage.set(201,"数据为空",new PageBeam<>(list));
        }
        return SetMessage.set(200,"成功",new PageBeam<>(list));
    }
}
